package cn.yangliu.gennerator;

import cn.yangliu.source.Source;

import java.util.*;

public abstract class AbstractGenerator<S extends Source> implements Generator<S> {

    protected CodeTemplate template;

    {
        template = new CodeTemplate();
    }

    protected String generateImports(String source, List<String> imports) {
        Set<String> set = new HashSet<>(imports);
        imports = new ArrayList<>(set);
        Collections.sort(imports);

        StringBuilder sb = new StringBuilder();
        for (String anImport : imports) {
            if (isJavaLangPackage(anImport)) {
                continue;
            }
            String code = template.t_import.replace("[import]", anImport);
            sb.append(code);
        }
        String code = sb.toString().trim();

        return source.replace("[imports]", code);
    }


    protected String generateAnnotations(String source, List<String> annotations) {
        Set<String> set = new HashSet<>(annotations);
        annotations = new ArrayList<>(set);
        Collections.sort(annotations);

        StringBuilder sb = new StringBuilder();
        for (String s : annotations) {
            sb.append("@").append(s).append("\n");
        }
        String code = sb.toString().trim();

        return source.replace("[annotations]", code);
    }

    protected String getClassPackage(String fullName) {

        if (fullName.contains(".")) {
            return fullName.substring(0, fullName.lastIndexOf("."));
        }
        return "";
    }

    protected String getClassShortName(String fullName) {
        if (fullName.contains(".")) {
            return fullName.substring(fullName.lastIndexOf(".") + 1);
        }
        return fullName;
    }


    protected boolean checkPackageIsSame(String firstPackage, String classFullName) {
        if (classFullName.contains(".") && !Objects.equals(firstPackage, "")) {
            String classPackage = classFullName.substring(classFullName.lastIndexOf(".") + 1);
            return Objects.equals(firstPackage, classPackage);
        }
        return false;
    }

    protected boolean isJavaLangPackage(String className) {
        String shortName = getClassShortName(className);
        return Objects.equals("java.lang." + shortName, className);
    }

}
